package com.base.service.impl;

import java.io.IOException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import com.base.entity.Member;
import com.base.entity.User;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RabbitListener(queues = {"java.queue"})
public class RabbitMqService {

	/**
	 * 监听java.queue队列消息
	 * 1:如果发送的是对象,接收的时候可以直接用对象接收
	 * 2:如果有多个消费者,同一个消息只能被一个消费者消费
	 * 3:消费者只有当一个消息处理完成,才能接收下一条消息
	 * @RabbitListener 可以标记在类+方法上
	 * @RabbitHandler 可以标记在方法上
	 * 
	 * @Title: recieveMessage
	 * @Description: 
	 * @Author xuyou
	 * @DateTime 2020年8月23日 下午5:43:29
	 * @param message
	 * @throws IOException 
	 */
	//@RabbitListener(queues = {"java.queue"})
	@RabbitHandler
	public void recieveMessage(Message message,User user,Channel channel) throws IOException {
		
		//接收到java.queue队列的消息:User(userId=11, userName=测试, nowDate=Sun Aug 23 18:11:03 CST 2020)
		
		//接收到java.queue队列的消息:
		/*(Body:'[B@67692ee7(byte[12])' 
		MessageProperties 
		[headers={}, 
		contentLength=0, 
		receivedDeliveryMode=PERSISTENT, 
		redelivered=false, 
		receivedExchange=java.direct.exchange, 
		receivedRoutingKey=java, 
		deliveryTag=1, 
		consumerTag=amq.ctag-PoWVh046hyVDJc36W83bcQ, 
		consumerQueue=java.queue])*/
		//channel通道按顺序内自增
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		
		try {
			//确定签收消息,false 是否批量签收
			channel.basicAck(deliveryTag, false);
		} catch (IOException e) {
			channel.basicNack(deliveryTag, 
					false, //是否批量签收
					true);//是否将此消息重新入队,false则把消息丢弃
			//basicReject功能和basicNack一致,只是不支持批量签收
			//channel.basicReject(deliveryTag, true);
		}

		log.info("接收到java.queue队列的消息user:{}",user);
	}
	
	@RabbitHandler
	public void recieveMessage(Member member) {
		log.info("接收到java.queue队列的消息:{}",member);
	}
}
